package com.tjh.springbootapi.config;

import com.koala.apiprototype.db.TenantContext;
import com.tjh.springbootapi.view.UserToken;

import javax.servlet.http.HttpServletRequest;

/**
 * 当前请求上下文
 * Create by koala on 2019-12-31
 */
public class ApiRequestContext {
    private ApiRequestContext() {
        //私有
    }

    //线程变量
    private static final ThreadLocal<ApiRequestContext> current = new ThreadLocal<>();

    //当前request
    private HttpServletRequest request;

    //当前登录的用户Id
    private UserToken userToken;

    public HttpServletRequest getRequest() {
        return request;
    }

    public String getUserId() {
        return userToken == null ? null : userToken.getUserId();
    }

    public String getToken() {
        return userToken == null ? null : userToken.getToken();
    }

    public UserToken getUserToken() {
        return userToken;
    }

    //初始化
    public static void init(HttpServletRequest request, UserToken userInfoView) {
        current.remove();
        ApiRequestContext context = new ApiRequestContext();
        context.userToken = userInfoView;
        context.request = request;
        current.set(context);
    }

    //获取当前线程的requestContext
    public static ApiRequestContext get() {
        return current.get();
    }

    //清除线程变量
    public static void clear() {
        current.remove();
        TenantContext.clear();
    }
}
